package cn.com.dashihui.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;

import cn.com.dashihui.kit.DirKit;
import cn.com.dashihui.kit.ValidateKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.ServiceShop;
import cn.com.dashihui.web.dao.ServiceShopImages;
import cn.com.dashihui.web.dao.ServiceShopItem;
import cn.com.dashihui.web.service.ServiceShopService;

public class ServiceShopController extends BaseController{
	
	private static final Logger logger = Logger.getLogger(ServiceShopController.class);
	private ServiceShopService shopService = new ServiceShopService();
	
	 /**
     * 转到商家管理主页面
     */
    public void index(){
        render("index.jsp");
    }
    
    /**
     * 商家管理主页面的分页数据
     */
    public void page(){
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		String name = getPara("name");
		int state = getParaToInt("state",0);
		renderResult(0,shopService.findByPage(pageNum, pageSize, getStoreid(), name, state));
	}
    
    /**
	 * 转到商家管理增加页面
	 */
	public void toAdd(){
		render("add.jsp");
	}
	
	/**
	 * 添加商家管理增加页面数据
	 */
	public void doAdd(){
		
		UploadFile thumb = getFile("thumb");
		//商户名称
		String name = getPara("name");
		//地址
		String address = getPara("address");
		//电话
		String tel = getPara("tel");
		//短简介
		String comment = getPara("comment");
		//商户状态
		String state = getPara("state");
		if(StrKit.isBlank(name)){
			renderResult(1);
			return;
		}else if(name.length()>100){
			renderResult(2);
			return;
		}else if(StrKit.notBlank(comment) && comment.length()>500){
			renderResult(3);
			return;
		}else if(StrKit.isBlank(state)){
			renderResult(4);
			return;
		}else if(!StrKit.isBlank(address) && address.length()>100){
			renderResult(5);
			return;
		}else if(!ValidateKit.Tel(tel) && !ValidateKit.Mobile(tel)){
			renderResult(6);
			return;
		}else{
			//保存
			ServiceShop shop = new ServiceShop()
						.set("name", name)
						.set("storeid", getStoreid())
						.set("address", address)
						.set("tel", tel)
						.set("state", Integer.valueOf(state).intValue());
			if(StrKit.notBlank(comment)){
				shop.set("comment", comment);
			}
			//如果上传了图片，则上传至FTP，并记录图片文件名
			if(thumb!=null){
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.SERVICE_SHOP);
				try {
					thumbFileName = uploadToFtp(dir,thumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(18);
					return;
				}
				shop.set("thumb", dir.concat(thumbFileName));
			}
			if(shopService.addShop(shop)){
				renderSuccess(shopService.findById(shop.getInt("id")));
				return;
			}
		}
		renderFailed();
	}
	
	/**
	  * 转到商家信息展示页面
	  */
	public void detail(){
		int id = getParaToInt(0,0);
		if(id != 0){
			setAttr("object", shopService.findById(id));
		}
		render("detail.jsp");
	}
	
	 /**
	  * 转到商家管理修改页面
	  */
	public void toEdit(){
		int id = getParaToInt(0,0);
		if(id != 0){
			setAttr("object", shopService.findById(id));
		}
		render("edit.jsp");
	}
	
	 /**
	  * 保存商家管理修改页面数据
	  */
	public void doEdit(){
		
		UploadFile thumb = getFile("thumb");
		//旧图片
		String thumbOld = getPara("thumbOld");
		//商铺id
		String shopid =  getPara("id");
		//商铺名称
		String name = getPara("name");
		//地址
		String address = getPara("address");
		//电话
		String tel = getPara("tel");
		//商铺短简介
		String comment = getPara("comment");
		//商铺状态
		String state = getPara("state");
		if(StrKit.isBlank(shopid)){
			renderFailed();
			return;
		}else if(StrKit.isBlank(name)){
			renderResult(1);
			return;
		}else if(name.length()>100){
			renderResult(2);
			return;
		}else if(StrKit.notBlank(comment) && comment.length()>500){
			renderResult(3);
			return;
		}else if(!StrKit.isBlank(address) && address.length()>100){
			renderResult(4);
			return;
		}else if(!ValidateKit.Tel(tel) && !ValidateKit.Mobile(tel)){
			renderResult(5);
			return;
		}else{
			//更新
			int id = Integer.valueOf(shopid).intValue();
			ServiceShop shop = new ServiceShop()
						.set("id", id)
						.set("name", name)
						.set("address", address)
						.set("tel", tel)
						.set("state", Integer.valueOf(state).intValue());
			if(thumb!=null){
				//如果修改了图片，则上传新图片，删除旧图片
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.SERVICE_SHOP);
				try {
					thumbFileName = uploadToFtp(dir,thumb);
					deleteFromFtp(thumbOld);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(6);
					return;
				}
				shop.set("thumb", dir.concat(thumbFileName));
			}
			if(StrKit.notBlank(comment)){
				shop.set("comment", comment);
			}
			if(shopService.editShop(shop)){
				renderSuccess();
				return;
			}
		}
		renderFailed();
	}
	
	/**
	 * 删除商铺(店铺门头图片,店铺所有图片,商铺与服务分类的关联,服务条目)
	 */
	@Before(Tx.class)
	public void doDelete(){
		int id = getParaToInt(0,0);
		if(id!=0){
			ServiceShop serShop = shopService.findById(id);
			//先判断商铺门头如果上传了图片，则删除图片
			if(!StrKit.isBlank(serShop.getStr("thumb"))){
				try {
					deleteFromFtp(serShop.getStr("thumb"));
				} catch (IOException e) {
					logger.error("删除时，相关图片"+serShop.getStr("thumb")+"删除失败！");
					e.printStackTrace();
				}
			}
			//删除商铺所有图片
			List<ServiceShopImages> listShopImages = shopService.findAllImages(id);
			try {
				for(ServiceShopImages shopimg : listShopImages){
					deleteFromFtp(shopimg.getStr("thumb"));
				}
			} catch (IOException e) {
				logger.error("批量删除图片失败");
				e.printStackTrace();
			}
			//删除商铺与服务分类的关联
			shopService.delCaShopRel(id);
			//服务
			shopService.delItemByShopid(id);
			//然后再对记录进行删除
			serShop.delete();
			renderSuccess();
			return;
		}
		renderFailed();
	}
	
	/**
	 *  转到 商铺选择服务分类 页面（比如：丽人 家政）
	 */
	public void toChoiceCategoryDialog(){
		int shopid = getParaToInt(0,0);
		setAttr("cList", shopService.findCategoryList(getStoreid(),shopid));
		setAttr("shopid", shopid);
		render("choiceCategory.jsp");
	}
	
	/**
	 *  保存 商铺选择服务分类 页面数据
	 */
	 @Before(Tx.class)
	public void addCaToShop(){
		String categorycode = getPara("categorycode");
		String shopid = getPara("shopid");
		if(StrKit.isBlank(shopid)){
			renderFailed();
			return;
		}else{
			shopService.addCaToShop(categorycode.split(","), Integer.valueOf(shopid).intValue());
			renderSuccess();
			return;
		}
	}
	 
	 /**
	 * 转到商铺产品修改详细内容页面
	 */
	public void toDetailEdit(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", shopService.findDetailById(id));
		}
		render("editorDetail.jsp");
	}
	
	 /**
	 * 保存商铺产品详情页面富文本编辑内容修改并保存数据
	 */
	public void doDetailEdit(){
		String id = getPara("id");
		String describe = getPara("describe");
		if(StrKit.isBlank(id)){
			renderResult(1);
			return;
		}
		ServiceShop shop = new ServiceShop()
				.set("id", Integer.valueOf(id).intValue())
				.set("describe", describe);
		if(shopService.editShop(shop)){
			renderSuccess();
			return;
		}
		renderFailed();
	}

	/**
	 * 商铺产品文本编辑中图片上传
	 */
	public void uploadimg(){
		UploadFile thumb = getFile();
		Map<String,Object> map = new HashMap<String,Object>();  
		if(thumb!=null){
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.SERVICE_SHOP_DETAIL);
			try {
				thumbFileName = uploadToFtp(dir,thumb);
				map.put("error", 0);  
				map.put("url",PropKit.get("constants.ftppath").concat(dir).concat(thumbFileName));  
				renderJson(map);
		        return;
			} catch (IOException e) {
				e.printStackTrace();
				logger.debug("上传图片失败");
				map.put("error", 1);  
				map.put("message","图片上传失败");  
				renderJson(map);
			}
		}else{
			map.put("error", 1);  
			map.put("message","图片为空");  
			renderJson(map);
		}
	}
	/*******************************************************************************************************/
	/*                                                商铺中图片增删改查                                                                                                   */
	/*******************************************************************************************************/	
	/**
	 * 转到商铺图片列表
	 */
	public void imageIndex(){
    	setAttr("shopid", getParaToInt(0));
        render("imageList.jsp");
    }
	/**
	 * 图片列表数据
	 */
    public void imgList(){
    	int shopid = getParaToInt(0);
    	renderResult(0,shopService.findAllImages(shopid));
    }

    /**
     * 商铺图片排序
     */
    public void doImageSort(){
    	Map<String,String[]> params = getParaMap();
    	if(params!=null&&params.size()!=0&&params.containsKey("sortKey")){
    		String sortKey = params.get("sortKey")[0];
    		Map<String,String> sortMap = new HashMap<String,String>();
    		for(String key : params.keySet()){
    			if(!key.equals("sortKey")){
    				String id = key.replace(sortKey, "");
    				String no = params.get(key)[0];
    				if(StrKit.isBlank(no)||no.length()>3){
    					no = "0";
    				}
    				sortMap.put(id, no);
    			}
    		}
    		if(sortMap.size()<=0){
    			renderResult(1);
    			return;
    		}else{
    			shopService.sortImages(sortMap);
    			renderSuccess();
    			return;
    		}
    	}
    	renderFailed();
    }
	    
    /**
     * 转到添加商铺图片页面
     */
	public void toImageAdd(){
		setAttr("shopid",getPara(0));
		render("imageAdd.jsp");
	}
	
	/**
	 * 保存添加商铺图片页面数据
	 */
	public void doImageAdd(){
		UploadFile thumb = getFile("thumb");
		int shopid = getParaToInt("shopid");
		//保存
		//如果上传了图片，则上传至FTP，并记录图片文件名
		if(thumb!=null){
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.SERVICE_SHOP_IMAGES);
			try {
				thumbFileName = uploadToFtp(dir,thumb);
			} catch (IOException e) {
				e.printStackTrace();
				renderResult(2);
				return;
			}
			ServiceShopImages image = new ServiceShopImages()
								.set("shopid", shopid)
								.set("thumb", dir.concat(thumbFileName));
			if(shopService.addImage(image)){
				renderSuccess(image);
				return;
			}
		}else{
			renderResult(1);
			return;
		}
	}
		
	/**
	 * 删除商铺图片
	 */
	public void doImageDelete(){
		int id = getParaToInt(0);
		if(id!=0){
			ServiceShopImages serShopImages = shopService.findImagesById(id);
			//先判断商铺图片如果上传了图片，则删除图片
			if(StrKit.notBlank(serShopImages.getStr("thumb"))){
				try {
					deleteFromFtp(serShopImages.getStr("thumb"));
					shopService.delImage(id);
					renderSuccess();
					return;
				} catch (IOException e) {
					logger.error("删除时，相关图片"+serShopImages.getStr("thumb")+"删除失败！");
					e.printStackTrace();
				}
			}
		}
		renderFailed();
	}
	
	/*******************************************************************************************************/
	/*                                                服务规格增删改查                                                                                                       */
	/*******************************************************************************************************/
	
	/**
	 * 转到服务规格主页面
	 */
	public void itemIndex(){
    	setAttr("shopid", getParaToInt(0));
        render("itemList.jsp");
    }
	
	/**
	 * 获得服务规格列表数据
	 */
    public void itemList(){
    	int shopid = getParaToInt(0);
    	renderResult(0,shopService.findAllItem(shopid));
    }
    
    /**
     * 转到服务规格增加页面
     */
    public void toItemAdd(){
    	setAttr("shopid", getParaToInt(0));
        render("itemAdd.jsp");
    }
    
    /**
     * 保存服务规格数据
     */
    public void doItemAdd(){
    	String title = getPara("title");
    	String shopid = getPara("shopid");
    	String marketPrice = getPara("marketPrice");
    	String sellPrice = getPara("sellPrice");
    	if(StrKit.isBlank(title)){
			renderResult(1);
			return;
		}else if(StrKit.isBlank(shopid)){
			renderResult(2);
			return;
		}else if(title.length()>100){
			renderResult(3);
			return;
		}else if(StrKit.notBlank(marketPrice) && marketPrice.length()>10){
			renderResult(4);
			return;
		}else if(StrKit.notBlank(sellPrice) && sellPrice.length()>10){
			renderResult(5);
			return;
		}else{
			ServiceShopItem item = new ServiceShopItem()
							.set("title",title)
							.set("shopid",Integer.valueOf(shopid).intValue());
			if(StrKit.notBlank(marketPrice)){
				item.set("marketPrice",Double.valueOf(marketPrice).doubleValue());
			}
			if(StrKit.notBlank(sellPrice)){
				item.set("sellPrice",Double.valueOf(sellPrice).doubleValue());
			}
			if(shopService.addItem(item)){
				renderSuccess();
				return;
			}
		}
    	renderFailed();
    }
    
    /**
     * 转到修改服务规格页面
     */
    public void toItemEdit(){
    	int id = getParaToInt(0);
    	setAttr("obj", shopService.findItemById(id));
        render("itemEdit.jsp");
    }
    
    /**
     * 修改服务规格数据
     */
    public void doItemEdit(){
    	String id = getPara("id");
    	String title = getPara("title");
    	String marketPrice = getPara("marketPrice");
    	String sellPrice = getPara("sellPrice");
    	if(StrKit.isBlank(id)){
    		renderResult(1);
			return;
    	}else if(StrKit.isBlank(title)){
			renderResult(2);
			return;
		}else if(title.length()>100){
			renderResult(3);
			return;
		}else if(StrKit.notBlank(marketPrice) && marketPrice.length()>10){
			renderResult(4);
			return;
		}else if(StrKit.notBlank(sellPrice) && sellPrice.length()>10){
			renderResult(5);
			return;
		}else{
			ServiceShopItem item = new ServiceShopItem()
							.set("id",Integer.valueOf(id).intValue())
							.set("title",title);
			if(StrKit.notBlank(marketPrice)){
				item.set("marketPrice",Double.valueOf(marketPrice).doubleValue());
			}
			if(StrKit.notBlank(sellPrice)){
				item.set("sellPrice",Double.valueOf(sellPrice).doubleValue());
			}
			if(shopService.updateItem(item)){
				renderSuccess();
				return;
			}
		}
    	renderFailed();
    }
    
    /**
     * 删除服务规格
     */
    public void doItemDelete(){
    	int id = getParaToInt(0);
    	if(shopService.delItem(id)){
			renderSuccess();
			return;
		}
    	renderFailed();
    }
}
